import React, { ReactElement, useState, useEffect } from 'react';
import { View, Animated, Easing, BackHandler } from 'react-native';
import ImagePicker, { Image } from 'react-native-image-crop-picker';

import styles from './style';
import { px } from '../../util/adapt';
import Button from '../Button';
import { modalClose, loading } from '../../util/global';

interface SelectPicProps {
  width?: number;
  height?: number;
  quality?: number;
  cropping?: boolean;
  action: (image: Image) => void | Promise<void>;
}

export default ({
  width = 195,
  height = 195,
  quality = 1,
  cropping = true,
  action
}: SelectPicProps): ReactElement => {
  const [bottomValue] = useState(new Animated.Value(px(-151)));

  useEffect((): void => {
    Animated.timing(bottomValue, {
      toValue: 0,
      duration: 100,
      easing: Easing.linear
    }).start();
  }, [bottomValue]);

  const handleBackButton = (): boolean => {
    modalClose();
    return true;
  };

  useEffect((): (() => void) => {
    BackHandler.addEventListener('hardwareBackPress', handleBackButton);
    return (): void => {
      BackHandler.removeEventListener('hardwareBackPress', handleBackButton);
    };
  }, []);

  return (
    <Animated.View style={[styles.container, { bottom: bottomValue }]}>
      <Button
        style={styles.button}
        text="从相册选择图片"
        textStyle={styles.buttonDesc}
        onPress={(): void => {
          ImagePicker.openPicker({
            width,
            height,
            cropping,
            includeBase64: true,
            compressImageQuality: quality,
            compressImageMaxWidth: width,
            compressImageMaxHeight: height,
            mediaType: 'photo',
            forceJpg: true
          }).then((image): void => {
            modalClose();
            loading.show();
            setTimeout((): void => {
              action(image);
              loading.hide();
            });
          });
        }}
      />
      <Button
        style={styles.button}
        text="拍照"
        textStyle={styles.buttonDesc}
        onPress={(): void => {
          ImagePicker.openCamera({
            width,
            height,
            cropping,
            includeBase64: true,
            compressImageQuality: quality,
            compressImageMaxWidth: width,
            compressImageMaxHeight: height,
            mediaType: 'photo',
            forceJpg: true
          }).then((image): void => {
            modalClose();
            loading.show();
            setTimeout((): void => {
              action(image);
              loading.hide();
            });
          });
        }}
      />
      <View style={styles.line} />
      <Button
        style={styles.button}
        text="取消"
        textStyle={styles.buttonDesc}
        onPress={modalClose}
      />
    </Animated.View>
  );
};
